package petertel.pbx.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import petertel.pbx.connector.Connection;
import petertel.pbx.connector.IShellCallback;

public class ConsoleServlet extends HttpServlet {

	private static final long serialVersionUID = 5498707040533452959L;

	@Override
	protected void service(HttpServletRequest req,
			final HttpServletResponse resp) throws ServletException,
			IOException {
		resp.setContentType("text/html");
		Connection conn = new Connection();
		conn.connect("tel", "tel", "os4test");
		conn.execute("tail -f /var/log/asterisk/messages",
				new IShellCallback() {

					public boolean processStdout(String line) {
						try {
							PrintWriter pw = resp.getWriter();
							pw.print(line
									+ "<script type='text/javascript'>document.write('<br />');document.body.lastChild.scrollIntoView();</script>");
							pw.flush();
							boolean error = pw.checkError();
							return !error;
						} catch (IOException e) {
							throw new RuntimeException(e);
						}
					}

					public boolean processStderr(String line) {
						return true;
					}

					public boolean isClosed() {
						try {
							return resp.getWriter().checkError();
						} catch (IOException e) {
							throw new RuntimeException(e);
						}
					}

				});
		conn.disconnect();
	}

}
